#define MSMD5_TOOLS_C
#include <sys/types.h>
#include <sys/stat.h>		//mkdir()
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <libmslog/mslog.h>
#include <libmscommon/mscommon.h>
#include <libmscommon/msmd5.h>
#include <libmscommon/msmd.h>


#define FLAG "MSMD5_TOOLS"

#define PRIVATEKEY_MSMD5	"msos@MSMD5&837611-54841523154654115465132154132154513212"
#define MAXSIZE_FILE 		(1*ms_GB)
int main(ms_u32 ms_in argc, ms_string * ms_in argv)
{
	mslog_api_init((mslog_level_more|mslog_enable_stdprint|mslog_enable_linefunc),ms_null,ms_null,ms_null);
	if(argc < 2){
		ms_errRet(-1, "格式：%s 文件名",argv[0]);
	}
	ms_string filename=argv[1];
	ms_s32 item1=0;
	ms_s32 item2=0;
ms_info("==========================摘要签名");
	ms_info("%d.检测文件%s是否存在?",(++item1),filename);
	if (access(filename,F_OK) < 0){
		ms_errRet(-1, "%d.%d.文件%s不存在，无法进行验算",(item1),(++item2),filename);
	}else{
		ms_debug("%d.%d.检测文件%s存在,继续",(item1),(++item2),filename);
	}
	ms_info("%d.组建计算摘要的数据",(++item1));
	ms_byte *file=ms_null;
	ms_mallocDes_retErr(-1, file, MAXSIZE_FILE, "file", "file");
	ms_strcpy(file, PRIVATEKEY_MSMD5);
	file[ms_strlen(PRIVATEKEY_MSMD5)]=0x0a;
	ms_s32 len=msmd_api_read3(filename, &file[ms_strlen(PRIVATEKEY_MSMD5)+1], MAXSIZE_FILE);
	if(!(len<MAXSIZE_FILE)){
		ms_errRet(-1, "Len error:%d",len);
	}
	ms_byte outMD5_signature[256]={0};
	ms_u64 len_input=len+ms_strlen(PRIVATEKEY_MSMD5)+1;
	ms_info("%d.数据长度为:%d",(++item1),len_input);
	msmd5_api_outStr(file, len_input, &outMD5_signature[128]);
	ms_info("%d.签名摘要:%s",(++item1),&outMD5_signature[128]);
ms_info("==========================摘要验签");
	item1=0;
	item2=0;
	ms_byte fileClac[1024]={0};
	ms_sprintfs(fileClac, "%s_clac", filename);
	ms_byte cmdline[1024]={0};
	ms_cmd(cmdline,"echo \"%s\" > %s",PRIVATEKEY_MSMD5,fileClac);
	ms_cmd(cmdline,"cat %s >> %s",filename,fileClac);
	ms_info("%d.检测文件%s是否存在?",(++item1),fileClac);
	if (access(filename,F_OK) < 0){
		ms_errRet(-1, "%d.%d.文件%s不存在，无法进行验算",(item1),(++item2),fileClac);
	}else{
		ms_debug("%d.%d.检测文件%s存在,继续",(item1),(++item2),fileClac);
	}
	ms_info("%d.组建计算摘要的数据",(++item1));
	len=msmd_api_read3(fileClac, file, MAXSIZE_FILE);
	if(!(len<MAXSIZE_FILE)){
		ms_errRet(-1, "Len error:%d",len);
	}
	ms_info("%d.数据长度为:%d",(++item1),len);
	ms_byte outMD5_visaVerification[128]={0};
	msmd5_api_outStr(file,len, outMD5_visaVerification);
	ms_info("%d.验签摘要:%s",(++item1),outMD5_visaVerification);
ms_info("==========================签名验签结果");
	if(ms_strncmp_saeq(&outMD5_signature[128], outMD5_visaVerification)){
		ms_info("通过");
	}else{
		ms_error("失败");
	}
	exit(0);
}
#undef MSMD5_TOOLS_C
